<template>
  <div class="container mt-4">
    <div class="card">
      <div class="card-header bg-primary text-white">
        <h4 class="mb-0">
          <i class="fas fa-edit mr-2"></i>
          {{ $route.params.id ? '编辑' : '添加' }}文化遗产
        </h4>
      </div>
      <div class="card-body">
        <el-form 
          :model="form" 
          :rules="rules" 
          ref="heritageFormRef" 
          label-width="100px"
          v-loading="loading"
          class="mt-3"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入文化遗产名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="类型" prop="type">
                <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%">
                  <el-option
                    v-for="type in types"
                    :key="type"
                    :label="type"
                    :value="type">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="地点" prop="location">
                <el-input v-model="form.location" placeholder="请输入地点"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年代" prop="year">
                <el-input v-model="form.year" placeholder="请输入年代"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="保护级别" prop="protectionLevel">
                <el-select v-model="form.protectionLevel" placeholder="请选择保护级别" style="width: 100%">
                  <el-option
                    v-for="level in protectionLevels"
                    :key="level"
                    :label="level"
                    :value="level">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="图片">
                <el-upload
                  class="avatar-uploader"
                  action="#"
                  :show-file-list="false"
                  :on-change="handleImageUpload"
                  :auto-upload="false">
                  <img v-if="currentImage" :src="currentImage" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="描述" prop="description">
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入描述信息"
              v-model="form.description">
            </el-input>
          </el-form-item>

          <el-form-item class="text-center">
            <el-button type="primary" @click="submitForm('heritageForm')">保存</el-button>
            <el-button @click="$router.push('/heritage')">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  listHeritage,
  createHeritage,
  updateHeritage
} from '@/api/api'

export default {
  name: 'HeritageEdit',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const loading = ref(false)
    const heritageFormRef = ref(null)
    
    const form = reactive({
      id: null,
      name: '',
      type: '',
      location: '',
      year: '',
      protectionLevel: '',
      description: '',
      imageUrl: ''
    })
    
    const types = ['建筑', '文物', '遗址', '民俗']
    const protectionLevels = ['国家级', '省级', '市级', '县级']
    const currentImage = ref(null)
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入文化遗产名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择类型', trigger: 'change' }
      ],
      location: [
        { required: true, message: '请输入地点', trigger: 'blur' },
        { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
      ],
      year: [
        { required: true, message: '请输入年代', trigger: 'blur' }
      ],
      protectionLevel: [
        { required: true, message: '请选择保护级别', trigger: 'change' }
      ],
      description: [
        { max: 500, message: '描述不能超过500个字符', trigger: 'blur' }
      ]
    }

    const fetchHeritage = async (id) => {
      try {
        loading.value = true
        const response = await listHeritage(id)
        if (response.status === 200 && response.data) {
          Object.assign(form, response.data)
          currentImage.value = response.data.imageUrl
        } else {
          throw new Error('获取数据失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败: ' + (error.message || '未知错误'))
        router.push('/heritage')
      } finally {
        loading.value = false
      }
    }

    const handleImageUpload = (uploadFile) => {
      if (uploadFile) {
        // 这里可以添加上传图片到服务器的逻辑
        // 上传成功后，将返回的图片URL赋值给form.imageUrl
        console.log('上传文件:', uploadFile)
        form.imageUrl = 'https://example.com/upload/' + uploadFile.name // 临时模拟
        currentImage.value = URL.createObjectURL(uploadFile.raw)
      }
    }

    const submitForm = async (formName) => {
      try {
        if (!heritageFormRef.value) return
        
        try {
          await heritageFormRef.value.validate()
        } catch (error) {
          console.error('表单验证失败:', error)
          return
        }
        
        loading.value = true
        const id = route.params.id
        let response
        
        if (id) {
          // 更新现有记录
          response = await updateHeritage(id, form)
        } else {
          // 创建新记录
          response = await createHeritage(form)
        }
        
        if (response.status === 200) {
          ElMessage.success('保存成功')
          router.push('/heritage')
        } else {
          throw new Error('保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败: ' + (error.response?.data?.message || error.message))
      } finally {
        loading.value = false
      }
    }

    onMounted(() => {
      // 如果是编辑模式，加载数据
      if (route.params.id) {
        fetchHeritage(route.params.id)
      }
    })

    return {
      loading,
      form,
      rules,
      types,
      protectionLevels,
      currentImage,
      heritageFormRef,
      handleImageUpload,
      submitForm
    }
  }
}
</script>

<style scoped>
/* 卡片样式 */
.card {
  border: none;
  border-radius: 15px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  background: linear-gradient(145deg, #ffffff 0%, #f8f9fa 100%);
}

/* 卡片头部样式 */
.card-header {
  background-color: #2c3e50;
  color: white;
  border-bottom: none;
  padding: 1.5rem 1.5rem 1rem;
  border-radius: 15px 15px 0 0;
}

.card-header h3 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.card-header i {
  color: #3498db;
  margin-right: 0.5rem;
  font-size: 1.2rem;
}

/* 表单样式 */
.form-group {
  margin-bottom: 1.75rem;
}

.form-group label {
  font-weight: 500;
  margin-bottom: 0.75rem;
  font-size: 0.95rem;
  color: #333;
}

.form-control {
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 0.85rem 1rem;
  font-size: 0.95rem;
  transition: all 0.3s ease;
}

.form-control:focus {
  border-color: #3498db;
  box-shadow: 0 0 0 0.2rem rgba(52, 152, 219, 0.25);
}

/* 选择框样式 */
select.form-control {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%236c757d' d='M6 8L2 4l1.5-1.5L6 5.25 9.5 1.75 11 3l-5 5z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 0.75rem center;
  background-size: 12px 12px;
  padding-right: 2.5rem;
}

/* 文本区域样式 */
textarea.form-control {
  min-height: 150px;
  resize: vertical;
  padding: 1rem;
}

/* 上传图片样式 */
.form-control-file {
  padding: 0.75rem;
  border: 1px dashed #e9ecef;
  border-radius: 8px;
  background: #f8f9fa;
  color: #6c757d;
  cursor: pointer;
  transition: all 0.3s ease;
}

.form-control-file:hover {
  background: #f1f3f5;
  border-color: #3498db;
}

/* 当前图片预览样式 */
.current-image {
  margin-top: 1rem;
  padding: 1rem;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  background: #f8f9fa;
}

.current-image img {
  max-width: 200px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 按钮样式 */
.btn {
  padding: 0.85rem 1.75rem;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 0.6rem;
}

.btn-primary {
  background-color: #3498db;
  border: none;
}

.btn-primary:hover {
  background-color: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.2);
}

.btn-secondary {
  background-color: #6c757d;
  border: none;
}

.btn-secondary:hover {
  background-color: #5a6268;
  transform: translateY(-1px);
}

/* 间距类 */
.mr-2 {
  margin-right: 0.75rem;
}

.mr-1 {
  margin-right: 0.5rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header h3 {
    font-size: 1.25rem;
  }
  
  .form-control {
    padding: 0.7rem 0.85rem;
    font-size: 0.9rem;
  }
  
  .btn {
    padding: 0.7rem 1.4rem;
    font-size: 0.9rem;
  }
  
  .form-group {
    margin-bottom: 1.5rem;
  }
}
</style>
